package order

import (
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/api"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/forms"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/models"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/order_web/proto"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"strconv"
)

func List(ctx *gin.Context) {
	idStr, _ := ctx.Get("id")
	uid, _ := idStr.(int64)
	claims, _ := ctx.Get("claims")
	model := claims.(*models.CustomClaims)

	req := proto.OrderFilterRequest{}
	// 如果是普通用户，则只能查询自己的订单
	if model.Role == 1 {
		req.UserId = uid
	}

	pageStr := ctx.DefaultQuery("pn", "0")
	page, _ := strconv.Atoi(pageStr)
	req.Pages = int64(page)
	pageNumStr := ctx.DefaultQuery("pnum", "0")
	pageNum, _ := strconv.Atoi(pageNumStr)
	req.Pages = int64(pageNum)

	resp, err := global.OrderSrvClient.OrderList(ctx, &req)
	if err != nil {
		zap.S().Errorw("[List] 查询 [订单列表] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	fmt.Println(resp)
	reMap := gin.H{
		"total": resp.Total,
	}
	orderList := make([]interface{}, 0)
	for _, item := range resp.Data {
		tmpMap := map[string]interface{}{}
		tmpMap["id"] = item.Id
		tmpMap["status"] = item.Status
		tmpMap["pay_type"] = item.PayType
		tmpMap["total"] = item.Total
		tmpMap["user"] = item.UserId
		tmpMap["address"] = item.Address
		tmpMap["name"] = item.Name
		tmpMap["mobile"] = item.Mobile
		tmpMap["post"] = item.Post
		tmpMap["order_sn"] = item.OrderSn
		tmpMap["add_time"] = item.AddTime

		orderList = append(orderList, tmpMap)
	}
	reMap["data"] = orderList

	ctx.JSON(200, reMap)
}

func New(ctx *gin.Context) {
	orderForm := forms.CreateOrderForm{}
	if err := ctx.ShouldBindJSON(&orderForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	idStr, _ := ctx.Get("id")
	uid, _ := idStr.(int64)
	rsp, err := global.OrderSrvClient.CreateOrder(ctx, &proto.OrderRequest{
		UserId:  uid,
		Name:    orderForm.Name,
		Mobile:  orderForm.Mobile,
		Address: orderForm.Address,
		Post:    orderForm.Post,
	})
	if err != nil {
		zap.S().Errorw("[New] 添加 [订单] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	client, err := alipay.New(global.ServerConfig.AlipayInfo.AppId, global.ServerConfig.AlipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Errorw("实例化支付宝失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	err = client.LoadAliPayPublicKey(global.ServerConfig.AlipayInfo.PublicKey)
	if err != nil {
		zap.S().Errorw("加载支付宝的公钥失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	var p = alipay.TradePagePay{}
	p.NotifyURL = global.ServerConfig.AlipayInfo.NotifyUrl
	p.ReturnURL = global.ServerConfig.AlipayInfo.ReturnUrl
	p.Subject = "DW生鲜订单-" + rsp.OrderSn
	p.OutTradeNo = rsp.OrderSn
	p.TotalAmount = strconv.FormatFloat(float64(rsp.Total), 'f', 2, 64)
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := client.TradePagePay(p)
	if err != nil {
		zap.S().Errorw("生成支付宝的url失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	ctx.JSON(200, gin.H{
		"id":         rsp.Id,
		"alipay_url": url.String(),
	})
}

func Detail(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		ctx.JSON(400, gin.H{
			"msg": "url格式出错",
		})
		return
	}
	uidStr, _ := ctx.Get("id")
	uid := uidStr.(int64)

	claims, _ := ctx.Get("claims")
	model := claims.(*models.CustomClaims)
	req := proto.OrderRequest{
		Id: id,
	}
	// 如果是普通用户，则只能查询自己的订单
	if model.Role == 1 {
		req.UserId = uid
	}
	resp, err := global.OrderSrvClient.OrderDetail(ctx, &req)
	if err != nil {
		zap.S().Errorw("[Detail] 查询 [订单详情] 失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	reMap := gin.H{
		"id":       resp.OrderInfo.Id,
		"status":   resp.OrderInfo.Status,
		"pay_type": resp.OrderInfo.PayType,
		"total":    resp.OrderInfo.Total,
		"user":     resp.OrderInfo.UserId,
		"address":  resp.OrderInfo.Address,
		"name":     resp.OrderInfo.Name,
		"mobile":   resp.OrderInfo.Mobile,
		"post":     resp.OrderInfo.Post,
		"order_sn": resp.OrderInfo.OrderSn,
		"add_time": resp.OrderInfo.AddTime,
	}
	goodsList := make([]interface{}, 0)
	for _, item := range resp.Goods {
		tmpMap := map[string]interface{}{}
		tmpMap["id"] = item.Id
		tmpMap["name"] = item.GoodsName
		tmpMap["image"] = item.GoodsImage
		tmpMap["price"] = item.GoodsPrice
		tmpMap["nums"] = item.Nums
		goodsList = append(goodsList, tmpMap)
	}
	reMap["goods"] = goodsList

	client, err := alipay.New(global.ServerConfig.AlipayInfo.AppId, global.ServerConfig.AlipayInfo.PrivateKey, false)
	if err != nil {
		zap.S().Errorw("实例化支付宝失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	err = client.LoadAliPayPublicKey(global.ServerConfig.AlipayInfo.PublicKey)
	if err != nil {
		zap.S().Errorw("加载支付宝的公钥失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	var p = alipay.TradePagePay{}
	p.NotifyURL = global.ServerConfig.AlipayInfo.NotifyUrl
	p.ReturnURL = global.ServerConfig.AlipayInfo.ReturnUrl
	p.Subject = "DW生鲜订单-" + resp.OrderInfo.OrderSn
	p.OutTradeNo = resp.OrderInfo.OrderSn
	p.TotalAmount = strconv.FormatFloat(float64(resp.OrderInfo.Total), 'f', 2, 64)
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := client.TradePagePay(p)
	if err != nil {
		zap.S().Errorw("生成支付宝的url失败")
		ctx.JSON(500, gin.H{
			"msg": err.Error(),
		})
		return
	}
	reMap["alipay_url"] = url.String()
	ctx.JSON(200, reMap)
}
